package com.xgkj.diyiketang.weidget;


import android.content.ContentResolver;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.util.PalLog;

import java.text.SimpleDateFormat;
import java.util.Date;


public class PullToRefreshListView extends ListView implements OnScrollListener {
	
	private static final String TAG = PullToRefreshListView.class.getSimpleName();

	public static final int IDLE = 0;

	public static final int PULL_REFRESH = 1;

	public static final int LOAD_MORE = 2;

	private final static int RELEASE_TO_REFRESH = 0;
	private final static int PULL_TO_REFRESH = 1;
	private final static int REFRESHING = 2;
	private final static int DONE = 3;

	private final static float RATIO = (float) 2.9;

	private LayoutInflater mInflater;

	private LinearLayout mHeadView;
//	private RelativeLayout mHeadView;

	private TextView mTvTips;

//	private TextView mTvUpdateTime;

	private ImageView mIvArrow;

	private ProgressBar mHeadProgress;

//	private RotateAnimation mRotateAnimation;
//	private RotateAnimation mResetRotateAnimation;

	private AnimationDrawable animation;//下拉刷新，上拉加载的动画

	private boolean mIsRecored;

    //private String mLastUpdateTime = "";
	
    //private String mLastUpdateTime_12 = "";

	private int mHeadContentHeight = -1;

	private int mImageHeight;

	private int mStartY;

	private int mFirstItemIndex;

	private int mLastItemIndex;

	private BaseAdapter mAdapter;

	private int mHeadState;

	private int mState;

	private boolean mIsBack;

	private OnRefreshListener mRefreshListener;
	private OnLoadDataListener mLoadDataListener;

	private boolean mIsRefreshable;

    private boolean mCanLoadMore = true;
    private boolean mEnableFootview = true;

	private View mFootView;

	private ProgressBar mFootProgress;

	private TextView mFootText;

//	private OnItemClickListener mOnItemClickListener;

//	private Animation alphaAnim_show, alphaAnim_hide;

	private Context mContext;
    private String mUpdateTimeKey;
    
    static final Interpolator ANIMATION_INTERPOLATOR = new LinearInterpolator();
    static final int FLIP_ANIMATION_DURATION = 150;

	public PullToRefreshListView(Context context) {
		super(context);
//		init(context,false);
	}

	public PullToRefreshListView(Context context, AttributeSet attrs) {
		super(context, attrs);
//		init(context,false);
	}
	
	boolean showView;

	public void init(Context context, boolean mIfViewHead) {
		mContext = context;
		showView = mIfViewHead;
		
		mInflater = LayoutInflater.from(context);

		mHeadView = (LinearLayout) mInflater.inflate(R.layout.refresh_item,
				null);

		mIvArrow = (ImageView) mHeadView
				.findViewById(R.id.my_pull_to_refresh_image);
		mIvArrow.setBackgroundResource(R.drawable.animation_load);
		animation = (AnimationDrawable)mIvArrow.getBackground();
		mHeadProgress = (ProgressBar) mHeadView
				.findViewById(R.id.my_pull_to_refresh_progress);
		mTvTips = (TextView) mHeadView.findViewById(R.id.my_pull_to_refresh_text);
//		mTvUpdateTime = (TextView) mHeadView
//				.findViewById(R.id.pull_to_refresh_updated_at);

		mHeadView.setPadding(0, -1 * mHeadContentHeight, 0, 0);
//		mHeadView.setBackgroundColor(getResources().getColor(R.color.dark_blue_button));
//		this.setHeaderDividersEnabled(false);
		addHeaderView(mHeadView);

		mFootView = mInflater.inflate(R.layout.foot_moreloading, null);
//		mFootView.setBackgroundColor(Color.TRANSPARENT);
		mFootProgress = (ProgressBar) mFootView.findViewById(R.id.foot_progress);
		mFootText = (TextView) mFootView.findViewById(R.id.foot_text);
		if (mFootProgress != null) {
			mFootProgress.setVisibility(View.GONE);
		}
		setOnScrollListener(this);

//		mRotateAnimation = new RotateAnimation(0, 180, Animation.RELATIVE_TO_SELF, 0.5f,
//				Animation.RELATIVE_TO_SELF, 0.5f);
//		mRotateAnimation.setInterpolator(ANIMATION_INTERPOLATOR);
//		mRotateAnimation.setDuration(FLIP_ANIMATION_DURATION);
//		mRotateAnimation.setFillAfter(true);

//		mResetRotateAnimation = new RotateAnimation(-180, 0, Animation.RELATIVE_TO_SELF, 0.5f,
//				Animation.RELATIVE_TO_SELF, 0.5f);
//		mResetRotateAnimation.setInterpolator(ANIMATION_INTERPOLATOR);
//		mResetRotateAnimation.setDuration(FLIP_ANIMATION_DURATION);
//		mResetRotateAnimation.setFillAfter(true);
		
//		mAnimation = new RotateAnimation(0, 180,
//				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
//				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
//		mAnimation.setInterpolator(new LinearInterpolator());
//		mAnimation.setDuration(2500);
//		mAnimation.setFillAfter(true);
//
//		mReverseAnimation = new RotateAnimation(180, 0,
//				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
//				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
//		mReverseAnimation.setInterpolator(new LinearInterpolator());
//		mReverseAnimation.setDuration(2000);
//		mReverseAnimation.setFillAfter(true);

		mHeadState = DONE;
		mIsRefreshable = false;
//        refreshUpdateTime();
	}
	public interface OnScrollListener {

		public void onScroll(AbsListView listView, int firstVisiableItem,
							 int visiableItemCount, int totalItemCount);

		public void onScrollStateChanged(AbsListView listView, int state);

	}

	private OnScrollListener mOnScrollListener;

	public void setOnScrollListener(OnScrollListener listener){
		mOnScrollListener = listener;
	}
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		
		if (mHeadContentHeight <= 0) {
			if(mHeadView != null)
			mHeadContentHeight = mHeadView.getMeasuredHeight();
			PalLog.e(TAG,"measure高度:"+mHeadContentHeight);
			changeHeaderViewByState();
        }
		if(!showView && mHeadContentHeight >0){
			showView = !showView;
			mHeadState = DONE;
            PalLog.d(TAG,"onMeasure"+ mHeadContentHeight);
			changeHeaderViewByState();
		}
	}

	public void onScroll(AbsListView arg0, int firstVisiableItem,
			int visiableItemCount, int totalItemCount) {

		if (mOnScrollListener != null){
			mOnScrollListener.onScroll(arg0,firstVisiableItem,visiableItemCount,totalItemCount);
		}
		mFirstItemIndex = firstVisiableItem;
		mLastItemIndex = visiableItemCount + firstVisiableItem - 1;
        if(visiableItemCount<totalItemCount&&getFooterViewsCount()==0 && mState==IDLE && mEnableFootview){
            addFooterView(mFootView);
        }
	}

	public void onScrollStateChanged(AbsListView arg0, int arg1) {

		if (mOnScrollListener != null){
			mOnScrollListener.onScrollStateChanged(arg0,arg1);
		}

		if (mAdapter != null) {
//            PalLog.e(TAG, "mLastItemIndex=" + mLastItemIndex);
//            PalLog.e(TAG, "mAdaptor.size=" + mAdapter.getCount());
//			PalLog.e(TAG, "mState:"+mState);
//            PalLog.d(TAG,"mCanLoadMore:"+mCanLoadMore);
			if (mLastItemIndex >= mAdapter.getCount()-1
					&& arg1 == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
					&& mState != LOAD_MORE && mState != PULL_REFRESH && mCanLoadMore) {
//				PalLog.e(TAG,"loadMore");
				if (mLoadDataListener != null) {
					setFootProgressVisible(true);
					mState = LOAD_MORE;
					mLoadDataListener.onLoadMore();
				}
			}
		}

	}

	public void enableRefresh() {
		mIsRefreshable = true;
	}

	public void disableRefresh() {
		mIsRefreshable = false;
	}

	public void enableLoadMore() {
        PalLog.d(TAG,"enableLoadMore");
		mCanLoadMore = true;
	}

	public void disableLoadMore() {
		mCanLoadMore = false;
	}

    public void enableFootview(){
        mEnableFootview = true;
    }

    public void disableFootview(){
        mEnableFootview = false;
        if(getFooterViewsCount()>0){
            removeFooterView(mFootView);
        }
    }
	public void doRefresh() {
        PalLog.d(TAG,"doRefresh");
		try {
			mHeadState = REFRESHING;
		} catch (Exception e) {
			e.printStackTrace();
		}
		mState = PULL_REFRESH;
        if(getFooterViewsCount()>0){
            removeFooterView(mFootView);
        }
        changeHeaderViewByState();
		onRefresh();

	}

	public void onRefreshComplete() {
//		refreshUpdateTime();
		cancelPullRefreshState();
        if(getFooterViewsCount()>0){
            removeFooterView(mFootView);
        }
	}

	public boolean onTouchEvent(MotionEvent event) {
//		PalLog.d(TAG,"onTouchEvent");
		if (!mIsRefreshable || mHeadState == REFRESHING) {
			return super.onTouchEvent(event);
		}

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN: {
			if (mFirstItemIndex == 0 && !mIsRecored) {

				mIsRecored = true;
				mStartY = (int) event.getY();
			}
			break;
		}
		case MotionEvent.ACTION_UP: {
			if (mHeadState == PULL_TO_REFRESH) {

				mHeadState = DONE;
				changeHeaderViewByState();
			} else if (mHeadState == RELEASE_TO_REFRESH) {

				mHeadState = REFRESHING;
				changeHeaderViewByState();

				if (mState == LOAD_MORE) {
					cancelLoadMoreState();
				}
				mState = PULL_REFRESH;
				if (mLoadDataListener != null)
					mLoadDataListener.onPullRefresh();
				onRefresh();
			}

			mIsRecored = false;
			mIsBack = false;
			break;
		}
		case MotionEvent.ACTION_MOVE: {
			int tempY = (int) event.getY();
			if (!mIsRecored && mFirstItemIndex == 0) {
				mIsRecored = true;
				mStartY = tempY;
			}

			if (mIsRecored) {
				int deltaY = tempY - mStartY;
				int headMiddleHeight = mHeadContentHeight - mImageHeight;

				if (mHeadState == RELEASE_TO_REFRESH) {

					setSelection(0);

					if (deltaY > 0 && ((deltaY / RATIO) < headMiddleHeight)) {
						mHeadState = PULL_TO_REFRESH;
						changeHeaderViewByState();
					}

					else if (tempY - mStartY <= 0) {
						mHeadState = DONE;
						changeHeaderViewByState();
					} else {

					}
				}

				else if (mHeadState == PULL_TO_REFRESH) {
					setSelection(0);

					if ((deltaY / RATIO) >= headMiddleHeight) {
						mHeadState = RELEASE_TO_REFRESH;
						mIsBack = true;
						changeHeaderViewByState();
					}

					else if (tempY - mStartY <= 0) {
						mHeadState = DONE;
						changeHeaderViewByState();
					}
				}

				else if (mHeadState == DONE) {
					if (deltaY > 0) {
						mHeadState = PULL_TO_REFRESH;
						changeHeaderViewByState();
					}
				}

				if (mHeadState == PULL_TO_REFRESH
						|| mHeadState == RELEASE_TO_REFRESH) {
					int paddingTop = (int) (-1 * mHeadContentHeight + deltaY
							/ RATIO);
					mHeadView.setPadding(0, paddingTop, 0, 0);
				}
			}
			break;
		}
		}

		return super.onTouchEvent(event);
	}

	public void setToIdleState() {
		if (mState == PULL_REFRESH) {
			cancelPullRefreshState();
		} else if (mState == LOAD_MORE) {
			cancelLoadMoreState();
		}

		mState = IDLE;
	}

	private void changeHeaderViewByState() {
        PalLog.d(TAG,"changeHeaderViewByState:"+mHeadState);
		if (mIvArrow == null)return;
		switch (mHeadState) {
		case RELEASE_TO_REFRESH:
			if(getHeaderViewsCount()==0)
				addHeaderView(mHeadView);
			mIvArrow.setVisibility(View.VISIBLE);
			mHeadProgress.setVisibility(View.GONE);
			mTvTips.setVisibility(View.VISIBLE);
			mTvTips.setText(R.string.pull_to_refresh_release_label);

			break;
		case PULL_TO_REFRESH:
			if(getHeaderViewsCount()==0)
				addHeaderView(mHeadView);
			mHeadProgress.setVisibility(View.GONE);
			mTvTips.setVisibility(View.VISIBLE);
			mIvArrow.setVisibility(View.VISIBLE);


			if (mIsBack) {
				mIsBack = false;
				mTvTips.setText(R.string.pull_to_refresh_pull_label);
			} else {
				mTvTips.setText(R.string.pull_to_refresh_pull_label);
			}

			break;
		case REFRESHING:
			if(getHeaderViewsCount()==0)
				addHeaderView(mHeadView);
			mHeadView.setPadding(0, 0, 0, 0);
			mHeadProgress.setVisibility(View.GONE);
			mIvArrow.setVisibility(View.VISIBLE);
			animation.start();
			mTvTips.setText(R.string.loading);
			break;
		case DONE:
			PalLog.e(TAG,mHeadContentHeight+"刷新完毕");
			mHeadView.setPadding(0, -1 * mHeadContentHeight, 0, 0);
			mHeadProgress.setVisibility(View.GONE);
			animation.stop();
			mIvArrow.setVisibility(View.GONE);
			mTvTips.setText(R.string.pull_to_refresh_pull_label);
			//动画可能出问题
			if(getHeaderViewsCount()>0 && mHeadContentHeight ==-1) {
				removeHeaderView(mHeadView);
			}
			break;
		}
	}

	private void refreshUpdateTime() {
        long time = 0;
        if (!TextUtils.isEmpty(mUpdateTimeKey)) {
//            time = MocamSetting.getInstance(mContext).getLastUpdateTime(mUpdateTimeKey);
        }
		ContentResolver cv = mContext.getContentResolver();
		String strTimeFormat = android.provider.Settings.System.getString(cv,
				android.provider.Settings.System.TIME_12_24);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
				if (strTimeFormat != null && strTimeFormat.equals("24")) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				}
        String format_date = sdf.format(new Date());
        if (time > 0) {
            format_date = sdf.format(new Date(time));
			}
//        String last_update_time = String.format(mContext.getString(R.string.last_update_time), format_date);
//        mTvUpdateTime.setText(last_update_time);
		}

	public void setOnRefreshListener(OnRefreshListener refreshListener) {
		mRefreshListener = refreshListener;
		mIsRefreshable = true;
	}

	public interface OnRefreshListener {
		public void onRefresh();
	}

	public interface OnLoadDataListener {
		public void onPullRefresh();

		public void onLoadMore();
	}

	public void setOnLoadDataListener(OnLoadDataListener listener) {
		mLoadDataListener = listener;
		mIsRefreshable = true;
	}

	public void onLoadDataComplete(boolean loadFinish) {
		if (mState == IDLE) {
			refreshUpdateTime();
			resetFooterView(!loadFinish);
		} else if (mState == PULL_REFRESH) {
			refreshUpdateTime();
			cancelPullRefreshState();
			resetFooterView(!loadFinish);
		} else if (mState == LOAD_MORE) {

			if (loadFinish) {
//				resetFooterView(false);
                cancelLoadMoreState();
			} else {
				setFootProgressVisible(false);
			}
		}

		mState = IDLE;
	}

	private void onRefresh() {
		if (mRefreshListener != null) {
			mRefreshListener.onRefresh();
		}
	}

	public int getState() {
		return mState;
	}

	public void setAdapter(BaseAdapter adapter, boolean needFootView) {
		super.setAdapter(adapter);
		mAdapter = adapter;
		if (adapter.getCount() > 0) {
			if (getFooterViewsCount() > 0) {
				removeFooterView(mFootView);
			}
		/*	if (needFootView) {
				addFooterView(mFootView);
			} */
		}

	}

	public View getFooterView() {
		return mFootView;
	}

	public void resetFooterView(boolean showFooterView) {
		if (showFooterView && getFooterViewsCount() == 0) {
			mFootProgress.setVisibility(View.GONE);
			addFooterView(mFootView);
		} else if (!showFooterView && getFooterViewsCount() > 0) {
			removeFooterView(mFootView);
		}
	}

	private void setFootProgressVisible(boolean v) {
		if(getFooterViewsCount() == 0){
			addFooterView(mFootView);
		}
        mFootText.setVisibility(View.VISIBLE);
		if (v) {
			mFootProgress.setVisibility(View.VISIBLE);
			mFootText.setText(R.string.get_more);
		} else {
			mFootProgress.setVisibility(View.GONE);
			mFootText.setText(R.string.get_more_fail);
			mFootView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
                    if (mLoadDataListener != null&&mFootText.getVisibility()==View.VISIBLE&&mFootText.getText().equals(mContext.getString(R.string.get_more_fail))) {
						setFootProgressVisible(true);
						mState = LOAD_MORE;
						mLoadDataListener.onLoadMore();
					}
					
				}
			});
		}
	}
	
	public void setNoNextPage(){
		if(getFooterViewsCount() == 0){
			addFooterView(mFootView);
		}
		mFootProgress.setVisibility(View.GONE);
		mFootText.setText(R.string.no_next_page);
		mFootText.setVisibility(View.VISIBLE);
		mState = IDLE;
        mCanLoadMore = false;
	}

	public void cancelPullRefreshState() {
        PalLog.d(TAG,"cancelPullRefreshState");
		if (mHeadState == REFRESHING) {
			mHeadState = DONE;
		}
        mState = IDLE;
		changeHeaderViewByState();
		
	}
	
	public void  cancelRefreshState(){
        PalLog.d(TAG,"cancelRefreshState");
		if(mHeadState != REFRESHING){
			mHeadState = DONE;
		}
        mState = IDLE;
		changeHeaderViewByState();
	}

	public void cancelLoadMoreState() {
        if(getFooterViewsCount()>0){
            removeFooterView(mFootView);
        }
        mState = IDLE;
		//mFootProgress.setVisibility(View.GONE);
		//mFootText.setText(R.string.get_more_success);
	}

    public void showHeaderView(){
        mHeadState = REFRESHING;
        changeHeaderViewByState();
    }
    public void hideHeaderView(){
        mHeadState = DONE;
        changeHeaderViewByState();

    }

    public void setUpdateTimeKey(String key){
        mUpdateTimeKey = key;
    }
}
